package com.dp.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dp.pub.SysProperty;
import com.dp.service.impl.ContentServiceImpl;
import com.dp.util.DataMap;
import com.dp.util.InterUtil;

public class ActiveSysParmServlet extends HttpServlet {
	
	private static Logger log = Logger.getLogger(ActiveSysParmServlet.class);
	/**
	 * Constructor of the object.
	 */
	public ActiveSysParmServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			response.setContentType("text/html;charset=utf-8");
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			DataMap dataMap = new DataMap();
			String[] load_params={"action/sys!mem.do","action/server!publishallcatlog.do","action/server!publishtitle.do","action/server!reloadsysparam.do","action/server!reloadWeather.do","action/server!reloadAllImageFile.do","action/server!reloadsystempicture.do","action/server!reloadFile.do","action/server!removeclient.do","action/server!publishtitle.do"};
			int loadType=-1;
			if(request.getParameter("loadType")!=null&&!"".equals(request.getParameter("loadType"))){
				try {
					loadType=Integer.parseInt(request.getParameter("loadType")); 
				} catch (NumberFormatException e) {
					e.printStackTrace();
					return;
				}
				
			}
			if(loadType<0||loadType>load_params.length){
				return;
			}
			dataMap.put("loadType", loadType);
			
			String idd="";
			String idtype="";
			if(loadType==7){
				if(request.getParameter("idd")!=null&&!"".equals(request.getParameter("idd"))){
					idd=request.getParameter("idd"); 
				}
				if(request.getParameter("idtype")!=null&&!"".equals(request.getParameter("idtype"))){
					idtype=request.getParameter("idtype"); 
				}
				load_params[loadType]+="?idd="+idd+"&&idtype="+idtype;
			}
			if(loadType==9){
				//手动执行5分钟刷新catlog到缓存
			    String updatetimer="0";
		        ContentServiceImpl contentServiceImpl=new ContentServiceImpl();
		        String channelidlist="";
		        channelidlist=contentServiceImpl.updateNctContentstatusByJob(updatetimer);
				if(!"".equals(channelidlist)){
					load_params[loadType]+="?channelidlist="+channelidlist;
				}else{
					PrintWriter out=response.getWriter();
					out.println("<html><head></head><body>");
					out.println("无内容更新");
					out.println("<center><a href='"+request.getContextPath()+"/jsp/base/activeSysParm.jsp'>返 回</a></center>");
					out.println("</body></html>");
					return;
				}
			}
			dataMap.put("load_param", load_params[loadType]);
			String temo_ss=remoteCallURL(dataMap);
			if(!"".equals(temo_ss)){
				PrintWriter out=response.getWriter();
				out.println("<html><head></head><body>");
				out.println(temo_ss);
				out.println("<center><a href='"+request.getContextPath()+"/jsp/base/activeSysParm.jsp'>返 回</a></center>");
				out.println("</body></html>");
				
			}
	}

	public String remoteCallURL(DataMap dataMap){
		String temo_ss="";
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }    
            temo_ss+="<br>"+i+"、";
            if(dataMap.get("load_param")!=null){
            	 url+=dataMap.get("load_param");
            }
            
            HttpURLConnection conn=null;
            BufferedReader in = null;
            try{
               URL testUrl = new URL(url);
               conn = (HttpURLConnection) testUrl.openConnection();
   			   conn.setRequestMethod("POST");
   			   int ret = conn.getResponseCode();
   			   if(ret==200){
   				   if(dataMap.get("loadType")!=null){
   					   if("0".equals(dataMap.get("loadType").toString())){
   						   temo_ss+=url;
   						   in = new BufferedReader(new InputStreamReader(conn
   								   .getInputStream(),"utf-8"));
   						   String temp = in.readLine();
   						   while (temp != null) {
   							   temo_ss+=temp;
   							   temp = in.readLine();
   						   }
   						   
   					   }
   				   }
   			   }
   			   	
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
                     if(dataMap.get("loadType")!=null&&!"0".equals(dataMap.get("loadType").toString())){
                    	 temo_ss+=ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url;
                     }
                     temo_ss+="<br>";
   		     }catch (Exception e) {
   		        	 log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");
                   	 temo_ss+=InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect"+"<br>";
   		     }finally {   
				if(in!=null){
					try {
						in.close();
					}catch(IOException e) {
						log.debug(e.getMessage()) ;
					}
				 }
   		         if (conn != null) {   
   		        		 conn.disconnect();   
   		         }   
   		    }    		
        }
	    
	    return temo_ss;
      
	 }
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
